package com.zjcloud.jwgl.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson2.JSON;
import com.zjcloud.common.utils.DateUtils;
import com.zjcloud.common.utils.SecurityUtils;
import com.zjcloud.jwgl.domain.JwglScheduleTask;
import com.zjcloud.jwgl.mapper.JwglScheduleTaskMapper;
import com.zjcloud.jwgl.service.IAcScheduleTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 智能排课任务Service业务层处理
 * 
 * @author zjcloud
 * @date 2024-12-19
 */
@Service
public class JwglAcScheduleTaskServiceImpl implements IAcScheduleTaskService 
{
    private static final Logger log = LoggerFactory.getLogger(JwglAcScheduleTaskServiceImpl.class);

    @Autowired
    @Qualifier("jwglJwglScheduleTaskMapper")
    private JwglScheduleTaskMapper acScheduleTaskMapper;

    /**
     * 查询智能排课任务
     * 
     * @param id 智能排课任务主键
     * @return 智能排课任务
     */
    @Override
    public JwglScheduleTask selectAcScheduleTaskById(Long id)
    {
        return acScheduleTaskMapper.selectAcScheduleTaskById(id);
    }

    /**
     * 查询智能排课任务列表
     * 
     * @param acScheduleTask 智能排课任务
     * @return 智能排课任务
     */
    @Override
    public List<JwglScheduleTask> selectAcScheduleTaskList(JwglScheduleTask acScheduleTask)
    {
        return acScheduleTaskMapper.selectAcScheduleTaskList(acScheduleTask);
    }

    /**
     * 新增智能排课任务
     * 
     * @param acScheduleTask 智能排课任务
     * @return 结果
     */
    @Override
    public int insertAcScheduleTask(JwglScheduleTask acScheduleTask)
    {
        acScheduleTask.setCreateTime(DateUtils.getNowDate());
        return acScheduleTaskMapper.insertAcScheduleTask(acScheduleTask);
    }

    /**
     * 修改智能排课任务
     * 
     * @param acScheduleTask 智能排课任务
     * @return 结果
     */
    @Override
    public int updateAcScheduleTask(JwglScheduleTask acScheduleTask)
    {
        acScheduleTask.setUpdateTime(DateUtils.getNowDate());
        return acScheduleTaskMapper.updateAcScheduleTask(acScheduleTask);
    }

    /**
     * 批量删除智能排课任务
     * 
     * @param ids 需要删除的智能排课任务主键
     * @return 结果
     */
    @Override
    public int deleteAcScheduleTaskByIds(Long[] ids)
    {
        return acScheduleTaskMapper.deleteAcScheduleTaskByIds(ids);
    }

    /**
     * 删除智能排课任务信息
     * 
     * @param id 智能排课任务主键
     * @return 结果
     */
    @Override
    public int deleteAcScheduleTaskById(Long id)
    {
        return acScheduleTaskMapper.deleteAcScheduleTaskById(id);
    }

    /**
     * 创建排课任务
     * 
     * @param taskName 任务名称
     * @param semester 学期
     * @param configData 配置数据
     * @return 任务ID
     */
    @Override
    @Transactional
    public Long createScheduleTask(String taskName, String semester, Map<String, Object> configData)
    {
        return createScheduleTask(taskName, null, semester, configData);
    }

    /**
     * 创建排课任务（支持学期ID）
     * 
     * @param taskName 任务名称
     * @param semesterId 学期ID
     * @param semester 学期名称
     * @param configData 配置数据
     * @return 任务ID
     */
    @Override
    @Transactional
    public Long createScheduleTask(String taskName, Long semesterId, String semester, Map<String, Object> configData)
    {
        try {
            JwglScheduleTask task = new JwglScheduleTask();
            task.setTaskName(taskName);
            task.setSemester(semester);
            task.setSemesterId(semesterId);
            task.setStatus(0); // 待执行
            task.setProgress(0);
            task.setConfigData(JSON.toJSONString(configData));
            task.setCreateBy(SecurityUtils.getUsername());
            task.setCreateTime(new Date());
            
            int result = acScheduleTaskMapper.insertAcScheduleTask(task);
            if (result > 0) {
                log.info("创建排课任务成功，任务ID: {}, 任务名称: {}, 学期: {}, 学期ID: {}", 
                        task.getId(), taskName, semester, semesterId);
                return task.getId();
            }
            return null;
        } catch (Exception e) {
            log.error("创建排课任务失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建排课任务失败: " + e.getMessage());
        }
    }

    /**
     * 启动排课任务
     * 
     * @param taskId 任务ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean startScheduleTask(Long taskId)
    {
        try {
            JwglScheduleTask task = acScheduleTaskMapper.selectAcScheduleTaskById(taskId);
            if (task == null) {
                log.warn("任务不存在，任务ID: {}", taskId);
                return false;
            }
            
            if (task.getStatus() != 0) {
                log.warn("任务状态不正确，无法启动，任务ID: {}, 当前状态: {}", taskId, task.getStatus());
                return false;
            }
            
            task.setStatus(1); // 执行中
            task.setStartTime(new Date());
            task.setUpdateBy(SecurityUtils.getUsername());
            task.setUpdateTime(new Date());
            
            int result = acScheduleTaskMapper.updateAcScheduleTask(task);
            if (result > 0) {
                log.info("启动排课任务成功，任务ID: {}", taskId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("启动排课任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 停止排课任务
     * 
     * @param taskId 任务ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean stopScheduleTask(Long taskId)
    {
        try {
            JwglScheduleTask task = acScheduleTaskMapper.selectAcScheduleTaskById(taskId);
            if (task == null) {
                log.warn("任务不存在，任务ID: {}", taskId);
                return false;
            }
            
            if (task.getStatus() != 1) {
                log.warn("任务状态不正确，无法停止，任务ID: {}, 当前状态: {}", taskId, task.getStatus());
                return false;
            }
            
            task.setStatus(3); // 失败
            task.setEndTime(new Date());
            task.setErrorMessage("用户手动停止任务");
            task.setUpdateBy(SecurityUtils.getUsername());
            task.setUpdateTime(new Date());
            
            int result = acScheduleTaskMapper.updateAcScheduleTask(task);
            if (result > 0) {
                log.info("停止排课任务成功，任务ID: {}", taskId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("停止排课任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 更新任务进度
     * 
     * @param taskId 任务ID
     * @param progress 进度百分比
     * @return 结果
     */
    @Override
    public boolean updateTaskProgress(Long taskId, Integer progress)
    {
        try {
            int result = acScheduleTaskMapper.updateTaskProgress(taskId, progress);
            return result > 0;
        } catch (Exception e) {
            log.error("更新任务进度失败，任务ID: {}, 进度: {}, 错误: {}", taskId, progress, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 完成任务
     * 
     * @param taskId 任务ID
     * @param resultData 结果数据
     * @return 结果
     */
    @Override
    @Transactional
    public boolean completeTask(Long taskId, Map<String, Object> resultData)
    {
        try {
            JwglScheduleTask task = acScheduleTaskMapper.selectAcScheduleTaskById(taskId);
            if (task == null) {
                log.warn("任务不存在，任务ID: {}", taskId);
                return false;
            }
            
            task.setStatus(2); // 已完成
            task.setProgress(100);
            task.setEndTime(new Date());
            task.setResultData(JSON.toJSONString(resultData));
            task.setUpdateBy(SecurityUtils.getUsername());
            task.setUpdateTime(new Date());
            
            int result = acScheduleTaskMapper.updateAcScheduleTask(task);
            if (result > 0) {
                log.info("完成排课任务成功，任务ID: {}", taskId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("完成排课任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 任务失败
     * 
     * @param taskId 任务ID
     * @param errorMessage 错误信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean failTask(Long taskId, String errorMessage)
    {
        try {
            JwglScheduleTask task = acScheduleTaskMapper.selectAcScheduleTaskById(taskId);
            if (task == null) {
                log.warn("任务不存在，任务ID: {}", taskId);
                return false;
            }
            
            task.setStatus(3); // 失败
            task.setEndTime(new Date());
            task.setErrorMessage(errorMessage);
            task.setUpdateBy(SecurityUtils.getUsername());
            task.setUpdateTime(new Date());
            
            int result = acScheduleTaskMapper.updateAcScheduleTask(task);
            if (result > 0) {
                log.info("标记排课任务失败成功，任务ID: {}, 错误信息: {}", taskId, errorMessage);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("标记排课任务失败失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 根据学期查询任务列表
     * 
     * @param semester 学期
     * @return 任务列表
     */
    @Override
    public List<JwglScheduleTask> selectTasksBySemester(String semester)
    {
        return acScheduleTaskMapper.selectTasksBySemester(semester);
    }

    /**
     * 查询正在执行的任务
     * 
     * @return 任务列表
     */
    @Override
    public List<JwglScheduleTask> selectRunningTasks()
    {
        return acScheduleTaskMapper.selectRunningTasks();
    }

    /**
     * 获取任务状态
     * 
     * @param taskId 任务ID
     * @return 任务状态信息
     */
    @Override
    public Map<String, Object> getTaskStatus(Long taskId)
    {
        JwglScheduleTask task = acScheduleTaskMapper.selectAcScheduleTaskById(taskId);
        Map<String, Object> result = new HashMap<>();
        
        if (task != null) {
            result.put("id", task.getId());
            result.put("taskName", task.getTaskName());
            result.put("semester", task.getSemester());
            result.put("status", task.getStatus());
            result.put("progress", task.getProgress());
            result.put("startTime", task.getStartTime());
            result.put("endTime", task.getEndTime());
            result.put("errorMessage", task.getErrorMessage());
            
            // 计算执行时间
            if (task.getStartTime() != null) {
                Date endTime = task.getEndTime() != null ? task.getEndTime() : new Date();
                long executionTime = endTime.getTime() - task.getStartTime().getTime();
                result.put("executionTime", executionTime);
            }
        }
        
        return result;
    }

    /**
     * 获取任务执行历史
     * 
     * @param semester 学期
     * @param limit 限制数量
     * @return 任务历史列表
     */
    @Override
    public List<JwglScheduleTask> getTaskHistory(String semester, Integer limit)
    {
        JwglScheduleTask queryTask = new JwglScheduleTask();
        queryTask.setSemester(semester);
        
        List<JwglScheduleTask> tasks = acScheduleTaskMapper.selectAcScheduleTaskList(queryTask);
        
        // 如果指定了限制数量，则只返回最近的记录
        if (limit != null && limit > 0 && tasks.size() > limit) {
            return tasks.subList(0, limit);
        }
        
        return tasks;
    }
}